package com.fastloan.safe.mgt.sys.controller;

import com.fastloan.safe.mgt.sys.model.CmuSysFile;
import com.fastloan.safe.mgt.sys.service.CmSysFileService;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import com.kawins.supers.file.IFileManager;
import com.kawins.supers.file.core.FileLoadBean;
import com.kawins.util.colle.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Set;

/**
 * @author rankai
 *         createTime 2017-10-2017/10/27 18:07
 */
@Controller
@RequestMapping("/api/cmSysFile")
public class CmSysFileController extends BaseController<CmuSysFile> {

    @Autowired
    private IFileManager fileService;

    @Autowired
    private CmSysFileService sysFileService;

    @GetMapping("/{fileId}")
    public ResponseEntity<byte[]> download(@PathVariable String fileId) {
        ResponseEntity<byte[]> download = fileService.download(fileId);
        return download;
    }

    /**
     * 根据文件ID获取文件
     *
     * @param fileId
     * @return
     */
    @GetMapping("/url/{fileId}")
    @ResponseBody
    public ResultTo select(@PathVariable String fileId) {
        String url = CmSysFileService.buildUri(sysFileService.selectByPrimaryKey(fileId));
        return new ResultTo().setData(url);
    }

    /**
     * 通用上传接口
     *
     * @param file
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultTo upload(MultipartFile[] file) {
        if (file == null || file.length == 0) {
            return new ResultTo(ResultEnum.PARAM_ERROR);
        }
        List<FileLoadBean> upload = fileService.upload(file);
        if (upload != null) {
            Set<Object> fileId = ListUtil.listField2Set("fileId", upload);
            Example example = new Example(CmuSysFile.class);
            example.createCriteria().andIn("id", fileId);
            List<CmuSysFile> cmuSysFiles = sysFileService.selectByExample(example);
            return new ResultTo().setData(cmuSysFiles);
        }
        return new ResultTo(ResultEnum.OPERATION_FAILED);
    }

    /**
     * 删除文件
     *
     * @param fileId
     * @return
     */
    @DeleteMapping("/{fileId}")
    @ResponseBody
    public ResultTo delete(@PathVariable String fileId) {
        fileService.delete(fileId);
        return new ResultTo();
    }
}
